package com.viewpagertext.service;

import static com.viewpagertext.activitys.MainActivity.btn_song_name;
import static com.viewpagertext.activitys.MainActivity.mList;
import static com.viewpagertext.activitys.MainActivity.playPosition;
import static com.viewpagertext.fragments.SongFragment.binding;
import static com.viewpagertext.app.ScrollShapeUIApplication.context;
import static com.viewpagertext.fragments.SongFragment.mTask;
import static com.viewpagertext.fragments.SongFragment.mTimer;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.widget.ImageView;
import android.widget.RemoteViews;

import androidx.core.app.NotificationCompat;

import com.bumptech.glide.Glide;
import com.viewpagertext.DBHelper.AppDatabase;
import com.viewpagertext.DBHelper.Dao.PlaybackModeDao;
import com.viewpagertext.DBHelper.Dao.StarredSongDao;
import com.viewpagertext.DBHelper.Helper.RecentPlayHelper;
import com.viewpagertext.Model.RecentPlay;
import com.viewpagertext.Model.UpdateUIEvent;
import com.viewpagertext.R;
import com.viewpagertext.constructor.ListToPlayEvent;
import com.viewpagertext.fragments.SongFragment;
import com.viewpagertext.json.StarredSong;
import com.viewpagertext.utils.TimeUtil;


import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.Random;
import java.util.Timer;


public class MusicService extends Service implements MediaPlayer.OnCompletionListener {
    /**,
     * 媒体播放器
     */
    /**
     * 歌曲间隔时间
     */
    public static boolean media_falg = false;
    private static final int INTERNAL_TIME = 1000;
    StarredSongDao helper = AppDatabase.getInstance().starredSongDao();
    PlaybackModeDao playbackModeHelper = AppDatabase.getInstance().playbackModeDao();
    RecentPlayHelper recentPlayHelper = new RecentPlayHelper();


    /**
     * 音乐播放器
     */
    public static MediaPlayer mediaPlayer;
    /**
     * 记录播放的位置
     */


    /**
     * 通知
     */
    private static Notification notification;
    /**
     * 通知栏视图
     */
    private static RemoteViews remoteViews;
    /**
     * 通知ID
     */
    private int NOTIFICATION_ID = 1;
    /**
     * 通知管理器
     */
    private static NotificationManager manager;
    /**
     * 音乐广播接收器
     */
    private MusicReceiver musicReceiver;

    private static final String TAG = "MusicService";
    /**
     * 歌曲播放
     */
    public static final String PLAY = "play";
    /**
     * 歌曲暂停
     */
    public static final String PAUSE = "pause";
    /**
     * 上一曲
     */
    public static final String PREV = "prev";
    /**
     * 下一曲
     */
    public static final String NEXT = "next";
    /**
     * 关闭通知栏
     */
    public static final String CLOSE = "close";
    /**
     * 进度变化
     */
    public static final String PROGRESS = "progress";

    /**
     * 注册动态广播
     */

    private void registerMusicReceiver() {
        musicReceiver = new MusicReceiver();
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnCompletionListener(this);

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(PLAY);
        intentFilter.addAction(PREV);
        intentFilter.addAction(NEXT);
        intentFilter.addAction(CLOSE);
        registerReceiver(musicReceiver, intentFilter);

    }


    /**
     * 广播接收器 （内部类）
     */
    public class MusicReceiver extends BroadcastReceiver {

        public static final String TAG = "MusicReceiver";

        @Override
        public void onReceive(Context context, Intent intent) {
            //UI控制
            UIControl(intent.getAction(), TAG);
        }

        /**
         * 页面的UI 控制 ，通过服务来控制页面和通知栏的UI
         *
         * @param state 状态码
         * @param tag
         */
        private void UIControl(String state, String tag) {
            switch (state) {
                case PLAY:
                    pauseOrContinueMusic();
                    break;
                case PREV:
                    previousMusic();
                    break;
                case NEXT:
                    nextMusic();
                    break;
                case CLOSE:
                    closeNotification();
                    break;
                default:
                    break;
            }
        }

    }

    /**
     * 初始化自定义通知栏 的按钮点击事件
     */
    private void initRemoteViews() {
        remoteViews = new RemoteViews(this.getPackageName(), R.layout.notification);

        //通知栏控制器上一首按钮广播操作
        Intent intentPrev = new Intent(PREV);
        PendingIntent prevPendingIntent = PendingIntent.getBroadcast(this, 0, intentPrev, 0);
        //为prev控件注册事件
        remoteViews.setOnClickPendingIntent(R.id.btn_notification_previous, prevPendingIntent);

        //通知栏控制器播放暂停按钮广播操作  //用于接收广播时过滤意图信息
        Intent intentPlay = new Intent(PLAY);
        PendingIntent playPendingIntent = PendingIntent.getBroadcast(this, 0, intentPlay, 0);
        //为play控件注册事件
        remoteViews.setOnClickPendingIntent(R.id.btn_notification_play, playPendingIntent);

        //通知栏控制器下一首按钮广播操作
        Intent intentNext = new Intent(NEXT);
        PendingIntent nextPendingIntent = PendingIntent.getBroadcast(this, 0, intentNext, 0);
        //为next控件注册事件
        remoteViews.setOnClickPendingIntent(R.id.btn_notification_next, nextPendingIntent);

        //通知栏控制器关闭按钮广播操作
        Intent intentClose = new Intent(CLOSE);
        PendingIntent closePendingIntent = PendingIntent.getBroadcast(this, 0, intentClose, 0);
        //为close控件注册事件
        remoteViews.setOnClickPendingIntent(R.id.btn_notification_close, closePendingIntent);

    }

    /**
     * 初始化通知
     */
    @SuppressLint("NotificationTrampoline")
    private void initNotification() {
        String channelId = "play_control";
        String channelName = "播放控制";
        int importance = NotificationManager.IMPORTANCE_HIGH;
        createNotificationChannel(channelId, channelName, importance);

        //点击整个通知时发送广播
        Intent intent = new Intent(getApplicationContext(), NotificationClickReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);

        //初始化通知
        notification = new NotificationCompat.Builder(this, "play_control")
                .setContentIntent(pendingIntent)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.bytemusic)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.bytemusic))
                .setCustomContentView(remoteViews)
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                .setAutoCancel(false)
                .setOnlyAlertOnce(true)
                .setOngoing(true)
                .build();
    }

    /**
     * 更改通知的信息和UI
     *
     * @param position 歌曲位置
     */
    public void updateNotificationShow(int position) {
        System.out.println("显示播放通知" + mList.get(position).getPic() + mList.get(position).getName());
        //播放状态判断
        if (mediaPlayer.isPlaying()) {
            remoteViews.setImageViewResource(R.id.btn_notification_play, R.drawable.pause_black);
        } else {
            remoteViews.setImageViewResource(R.id.btn_notification_play, R.drawable.play_black);
        }
        //封面专辑
        remoteViews.setImageViewBitmap(R.id.iv_album_cover, getAlbumPicture(this, mList.get(position).getPic()));
        //歌曲名
        remoteViews.setTextViewText(R.id.tv_notification_song_name, mList.get(position).getName());
        //歌手名
        remoteViews.setTextViewText(R.id.tv_notification_singer, mList.get(position).getSinger());

        EventBus.getDefault().post(new UpdateUIEvent(1, mList.get(position).getName(), mList.get(position).getSinger(), mList.get(position).getPic()));
        //发送通知给MainActivity叫他修改

        //发送通知
        initNotification();
        manager.notify(NOTIFICATION_ID, notification);
    }


    /**
     * 显示通知
     */
    private void showNotification() {
        //点击整个通知时发送广播
        Intent intent = new Intent(getApplicationContext(), NotificationClickReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);

        String channelId = "play_control";
        String channelName = "播放控制";
        int importance = NotificationManager.IMPORTANCE_HIGH;
        createNotificationChannel(channelId, channelName, importance);
//        RemoteViews remoteViews = new RemoteViews(this.getPackageName(), R.layout.notification);

        Notification notification = new NotificationCompat.Builder(this, "play_control")
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.bytemusic)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.bytemusic))
                .setCustomContentView(remoteViews)
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                .setAutoCancel(false)
                .setOnlyAlertOnce(true)
                .setOngoing(true)
                .build();
        //发送通知
        manager.notify(1, notification);
    }

    /**
     * 创建通知渠道
     *
     * @param channelId   渠道id
     * @param channelName 渠道名称
     * @param importance  渠道重要性
     */
    @TargetApi(Build.VERSION_CODES.O)
    private void createNotificationChannel(String channelId, String channelName, int importance) {
        NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
        channel.enableLights(false);
        channel.enableVibration(false);
        channel.setVibrationPattern(new long[]{0});
        channel.setSound(null, null);
        //获取系统通知服务
        manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.createNotificationChannel(channel);
    }

    public class MusicBinder extends Binder {
        public MusicService getService() {
            return MusicService.this;
        }
    }


    @Override
    public IBinder onBind(Intent intent) {
        return new MusicBinder();
    }

    @Override
    public void onCreate() {
        super.onCreate();

        initRemoteViews();
        //注册动态广播
        registerMusicReceiver();

        showNotification();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (musicReceiver != null) {
            //解除动态注册的广播
            unregisterReceiver(musicReceiver);
        }
    }


    //获取专辑pic

    /**
     * 获取专辑封面
     *
     * @param context 上下文
     * @param path    歌曲路径
     * @return
     */
    public static Bitmap getAlbumPicture(Context context, String path) {
        //歌曲检索
        MediaMetadataRetriever mmr = new MediaMetadataRetriever();
        byte[] data;
        //设置数据源
        try {
            // 尝试设置数据源
            mmr.setDataSource(path);
            // ... 其他代码
        } catch (RuntimeException e) {
            // 处理异常，可能是日志记录或显示错误消息
            System.out.println("处理异常");
            e.printStackTrace();
            data = null;
        }
        //获取图片数据
        data = mmr.getEmbeddedPicture();
        Bitmap albumPicture = null;
        if (data != null) {
            //获取bitmap对象
            albumPicture = BitmapFactory.decodeByteArray(data, 0, data.length);
            //获取宽高
            int width = albumPicture.getWidth();
            int height = albumPicture.getHeight();
            // 创建操作图片用的Matrix对象
            Matrix matrix = new Matrix();
            // 计算缩放比例
            float sx = ((float) 120 / width);
            float sy = ((float) 120 / height);
            // 设置缩放比例
            matrix.postScale(sx, sy);
            // 建立新的bitmap，其内容是对原bitmap的缩放后的图
            albumPicture = Bitmap.createBitmap(albumPicture, 0, 0, width, height, matrix, false);
        } else {
            //从歌曲文件读取不出来专辑图片时用来代替的默认专辑图片
            albumPicture = BitmapFactory.decodeResource(context.getResources(), R.mipmap.bytemusic);
            int width = albumPicture.getWidth();
            int height = albumPicture.getHeight();
            // 创建操作图片用的Matrix对象
            Matrix matrix = new Matrix();
            // 计算缩放比例
            float sx = ((float) 120 / width);
            float sy = ((float) 120 / height);
            // 设置缩放比例
            matrix.postScale(sx, sy);
            // 建立新的bitmap，其内容是对原bitmap的缩放后的图
            albumPicture = Bitmap.createBitmap(albumPicture, 0, 0, width, height, matrix, false);
        }
        return albumPicture;
    }

    public static int Comcount = 0;

    @SuppressLint("SuspiciousIndentation")
    @Override
    public void onCompletion(MediaPlayer mp) {
        //下一曲
        String currentMode = playbackModeHelper.getCurrentPlaybackMode(); // 读取当前播放模式
        System.out.println("这首播放完成了");
        media_falg = true;
        System.out.println("最大" + helper.getMaxId());
        if (helper.getMaxId() != 0 && mediaPlayer.getDuration() != 0)
            switch (currentMode) {
                case "list":
                    nextMusic();
                    break;
                case "random":
                    Random random = new Random();
                    int randomNumber;
                    do {
                        randomNumber = random.nextInt(mList.size());
                    } while (randomNumber == playPosition);
                    playPosition = randomNumber;
                    play(playPosition);
                    break;
                case "single":
                    System.out.println("单曲播放");
                    //单曲播放，此时可以不用重新播放，否则会消耗
                    play(playPosition);
                    break;
                default:
                    nextMusic();
                    break;
            }


    }

    /**
     * 播放
     */
    @SuppressLint("SuspiciousIndentation")
    public void play(int position) {
        System.out.println("播放音乐" + mList.get(position).getName() + position);

        if (mediaPlayer == null) {
            mediaPlayer = new MediaPlayer();
            //监听音乐播放完毕事件，自动下一曲
            mediaPlayer.setOnCompletionListener(this);
        }
        //需要播放时 获取当前歌曲列表是否有歌曲

        if (mList.size() <= 0) {
            System.out.println("播放列表大小小于零");
            return;
        }
            EventBus.getDefault().postSticky(new ListToPlayEvent(mList.get(playPosition).getPic(), mList.get(playPosition).getName(),
                    mList.get(playPosition).getSinger(), mList.get(playPosition).getLrc(),
                    mList.get(playPosition).getUrl(), TimeUtil.formatSeconds(mList.get(playPosition).getTime()),
                    mList.get(playPosition).getSongId()));

        try {

            //切歌前先重置，释放掉之前的资源
            mediaPlayer.reset();
            playPosition = position;
            //设置播放音频的资源路径；
            String url = mList.get(position).getUrl();
            System.out.println("得到url路径" + url);
            if (url.contains("#@!")) url = url.split("#@!")[0];
            mediaPlayer.setDataSource(url);
            if (url.startsWith("http"))
                mediaPlayer.prepareAsync();
            else mediaPlayer.prepare();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    System.out.println("准备好了");
                    if (mediaPlayer.getDuration() != 0 && binding != null)
                        binding.playTime.setText(TimeUtil.formatSeconds(mediaPlayer.getDuration() / 1000));
                    mp.start();
                    StarredSong playingSong = mList.get(playPosition);
                    RecentPlay recentPlay = new RecentPlay();
                    recentPlay.name = playingSong.getName();
                    recentPlay.singer = playingSong.getSinger();
                    recentPlay.album = playingSong.getName();
                    recentPlay.path = playingSong.getUrl();
                    recentPlay.time = playingSong.getTime();
                    recentPlay.lrc = playingSong.getLrc();
                    recentPlay.pic = playingSong.getPic();
                    recentPlay.songId = playingSong.getSongId();
                    recentPlayHelper.insertRecentPlayEntity(recentPlay);
                    //显示通知
                    updateNotificationShow(position);

                }
            });

            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    System.out.println("发生错误");
                    System.out.println("onError what: " + what + "  extra: " + extra);
                    return true;
                }
            });

        } catch (IOException e) {
            System.out.println("错误发生");
            e.printStackTrace();
        }
    }


    /**
     * 上一首
     */
    public void previousMusic() {
        mList = helper.getAllStarredSongs();
        if (playPosition >= mList.size() - 1) {
            playPosition = 0;
        } else {
            playPosition += 1;
        }

        play(playPosition);
    }

    /**
     * 暂停/继续 音乐
     */
    public void pauseOrContinueMusic() {

        if (btn_song_name.getText().toString().isEmpty()) {
            play(mList.size() - 1);
        } else if (mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
        } else {
            mediaPlayer.start();
        }
        //判断是否有播放，如果是第一次播放，就选择找一下

        //更改通知栏播放状态
        updateNotificationShow(playPosition);
    }

    /**
     * 关闭音乐通知栏
     */
    public void closeNotification() {
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
            }
        }
        manager.cancel(NOTIFICATION_ID);
    }

    /**
     * 下一首
     */
    public void nextMusic() {

        mList = helper.getAllStarredSongs();

        for (StarredSong s : mList) {
            System.out.println("wwwwww" + s.getName() + s.getUrl());
        }
        System.out.println("进行下一首" + playPosition);
        if (playPosition <= 0) {
            playPosition = mList.size() - 1;
        } else {
            playPosition -= 1;
        }
        play(playPosition);
    }


}

